<template>
  <div>
    <Form
      ref="formData"
      :model="formData"
      :rules="formDataRules"
      :label-width="140"
    >
      <Card title="新增知识点" dis-hover class="ivu-mt">
        <Row>
          <Col span="18" offset="2">
            <FormItem label="知识点名称" prop="knowledgeName">
              <Input
                v-model.trim="formData.knowledgeName"
                placeholder="请输入标签名称"
              ></Input>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="知识点类型" prop="knowledgeType">
              <Select v-model="formData.knowledgeType">
                <Option
                  v-for="item in KnowledgeTypeList"
                  :value="item.knowledgeType"
                  :key="item.knowledgeType"
                  >{{ item.knowledgeTypeName }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="上传附件">
              <Upload
                ref="uploadFile"
                action="/sysback/fileserver/uploadfile"
                name="myfile"
                :on-success="handleFileSuccess"
                :before-upload="handleBeforeFileUpload"
              >
                <Button icon="ios-cloud-upload-outline">点击上传</Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="上传图片">
              <UploadImg
                class="ivu-mr qw-disflex"
                :defaultList="defaultList"
                :mr="16"
                :maxSize="2048"
                :maxLen="5"
                :format="['jpg', 'jpeg', 'png']"
                @handleChangeImage="changeImageKey"
              >
              </UploadImg>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="状态" prop="state">
              <RadioGroup v-model="formData.state">
                <Radio label="1">启用</Radio>
                <Radio label="2">禁用</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="介绍" prop="note">
              <Input
                v-model="formData.note"
                type="textarea"
                maxlength="100"
                show-word-limit
                :autosize="{ minRows: 2, maxRows: 5 }"
                placeholder="请输入介绍内容"
              />
            </FormItem>
          </Col>
          <Col span="18" offset="2">
            <FormItem label="">
              <Button
                type="primary"
                :loading="rLoading"
                @click="toRelease('formData')"
                >提交</Button
              >
              <Button @click="goBack" class="ivu-ml">取消</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
    </Form>
    <Modal title="预览图片" v-model="visible">
      <img :src="imageUrl" v-if="visible" style="width: 100%" />
    </Modal>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import UploadImg from '@/components/common/upload'; // 上传组件
export default {
  components: { UploadImg },
  data () {
    return {
      requestApi: {
        // 视情况自定义
        // 新增知识点
        baseAdd: {
          url: '/sysback/knowledgebase/baseAdd', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 获取知识点类型
        getKnowledgeType: {
          url: '/sysback/knowledgebase/getKnowledgeType', // 接口地址
          type: 'get' // 接口请求类型
        }
      },
      rLoading: false,
      KnowledgeTypeList: [],
      formData: {
        knowledgeName: '', // 知识点名称
        knowledgeTypeName: '', // 知识点类型名称
        knowledgeType: '', // 知识点类型
        attachment: '', // 上传的文件
        state: '1', // 启用状态 1启用2禁用
        stateName: '启用', // 启用状态名称
        note: '' // 介绍
      },
      uploadFileList: [],
      formDataRules: {
        knowledgeName: [
          { required: true, message: '请输入知识点名称', trigger: 'blur' },
          {
            type: 'string',
            min: 2,
            max: 100,
            message:
              '文字最多输入100个字符，最少输入2个字符（汉字、英文字母、标点、数字均算一个字符）',
            trigger: 'blur'
          }
        ],
        knowledgeType: [
          { required: true, message: '请选择知识点类型', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请输入知识点名称', trigger: 'blur' }
        ],
        note: [{ required: true, message: '请填写介绍信息', trigger: 'blur' }]
      },
      uploadList: [], // 上传展示的图片
      imageList: [],
      visible: false, // 是否显示预览
      imageUrl: '', // 预览图片地址,
      defaultList: []
    };
  },
  mounted () {
    this.getKnowledgeType();
    this.uploadFileList = this.$refs.uploadFile.fileList;
  },
  methods: {
    changeImageKey (imgArr) {
      this.defaultList = imgArr;
    },
    // 上传附件start
    handleFileSuccess (res, file) {
      this.formData.attachment = res.retData;
    },
    handleBeforeFileUpload () {
      const check = this.uploadFileList.length < 1;
      if (!check) {
        this.$Notice.warning({
          title: '上传文件达到最大限制.'
        });
      }
      return check;
    },
    // 上传附件end
    // 上传图片部分start
    handleSuccess (res, file) {
      file.url = this.imgBaseURL + res.retData;
      file.name = res.retData.realName;
      file.imageKey = res.retData;
      this.imageList.push(res.retData);
    },
    handleFormatError (file) {
      let fileType = this.format.join(',');
      this.$Notice.warning({
        title: this.fileType + '格式不正确',
        desc:
          this.fileType +
          file.name +
          '格式不正确, 请选择' +
          fileType +
          '格式的.' +
          this.fileType
      });
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc:
          '图片  ' +
          file.name +
          ' 太大了, 请确保图片在' +
          this.fileCon.maxSize +
          'kb以内.'
      });
    },
    handleBeforeUpload () {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Notice.warning({
          title: '上传图片达到最大限制.'
        });
      }
      return check;
    },
    handleView (url) {
      this.imageUrl = url;
      this.visible = true;
    },
    handleRemove (file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    // 上传图片部分end

    // 获取知识点类型数据
    getKnowledgeType () {
      ApiRequest(
        this.requestApi.getKnowledgeType.url,
        this.requestApi.getKnowledgeType.type,
        {},
        false
      ).then(res => {
        if (res.retStatus === '1') {
          this.KnowledgeTypeList = res.retData;
        }
      });
    },
    // 提交新增
    toRelease (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.rLoading = true;
          let data = this.formData;
          if (data.state == '1') {
            data.stateName = '启用';
          } else {
            data.stateName = '禁用';
          }
          if (this.KnowledgeTypeList && this.KnowledgeTypeList.length > 0) {
            this.KnowledgeTypeList.forEach(item => {
              if (item.knowledgeType == data.knowledgeType) {
                data.knowledgeTypeName = item.knowledgeTypeName;
              }
            });
          }
          let pic = 'pic';
          if (this.defaultList && this.defaultList.length > 0) {
            this.defaultList.forEach((item, index) => {
              data[pic + (index + 1)] = item.url;
            });
          }
          ApiRequest(
            this.requestApi.baseAdd.url,
            this.requestApi.baseAdd.type,
            data,
            false
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('新增知识点成功!');
              this.$router.go(-1);
            }
            this.rLoading = false;
          });
        }
      });
    },
    goBack () {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="less" scoped>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
